﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using FileManager.Model;
using FileManager.MyProcess;
using FileManager.Util;
using Microsoft.Win32;
using MyPinYin;
using MysToolCore;
using Newtonsoft.Json.Linq;
using Stateless;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using static FileManager.Util.GlobalData;

namespace FileManager.ViewModel
{
    internal partial class BookWindowViewModel : ObservableObject
    {

        /// <summary>
        /// 从xml文件导入元数据信息
        /// </summary>
        [RelayCommand]
        private void ReadPic()
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            openFileDialog.Filter = "Png文件|*.png;*.jpg";
            openFileDialog.ShowDialog();
            if (openFileDialog.FileNames.Count() == 0)
                return;
            ImgNow = BitmapToBitmapImage(openFileDialog.FileName);
            Idx = 1;
        }

        /// <summary>
        /// 从xml文件导入元数据信息
        /// </summary>
        [RelayCommand]
        private void ReadPicDir()
        {
            OpenFolderDialog openFolderDialog = new OpenFolderDialog();
            openFolderDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            if (!(openFolderDialog.ShowDialog()??false))
                return;
            string dirPath = openFolderDialog.FolderName;
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            LetterList.Clear();

            List<string> picNames = new List<string>();

            picNames.AddRange(Directory.GetFiles(dirPath, "*.jpg"));
            picNames.AddRange(Directory.GetFiles(dirPath, "*.png"));
            foreach (string picPath in picNames)
            {
                string path = picPath;
                string name= Path.GetFileNameWithoutExtension(picPath);
                LetterList.Add(new Letter(name, picPath));
            }
            if (LetterList.Count > 0)
            {
                Idx = 1;
                ShowInfo();
            }
            UpdateFileInfo();
        }

        [RelayCommand]
        private void ImpNewBook()
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            openFileDialog.Title = "请打开XML清单文件";
            openFileDialog.Filter = "*.xml|*.xml";
            openFileDialog.ShowDialog();
            if (openFileDialog.FileNames.Count() == 0)
                return;
            string filePath = openFileDialog.FileName;
            XmlFile = filePath;
            LetterDatas = LetterDataUtils.LoadFromFile(filePath);
            var temp = LetterDatas.ToCloneEnumerable();
            LetterList.Clear();
            temp.ToList().ForEach(x => LetterList.Add(x));

            OpenFolderDialog openFolderDialog = new OpenFolderDialog();
            openFolderDialog.Title = "请打开委托书文件夹";
            openFolderDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            if (!(openFolderDialog.ShowDialog() ?? false))
                return;
            string dirPath = openFolderDialog.FolderName;
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            LetterList.Clear();
            List<string> picNames = new List<string>();
            picNames.AddRange(Directory.GetFiles(dirPath, "*.jpg"));
            picNames.AddRange(Directory.GetFiles(dirPath, "*.png"));
            foreach (string picPath in picNames)
            {
                string path = picPath;
                string name = Path.GetFileNameWithoutExtension(picPath);
                LetterList.Add(new Letter(name, picPath));
            }
            if (LetterList.Count > 0)
            {
                Idx = 1;
                ShowInfo();
            }
            UpdateFileInfo();
        }

        private void ImpDw()
        {
            UpdateFileInfo();
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Filter = "单位文本|*.txt";
            openFileDialog.ShowDialog();
            if (openFileDialog.FileNames.Count() == 0)
                return;
            string filePath = openFileDialog.FileName;
            using (var sr = new StreamReader(new FileStream(filePath, FileMode.Open), Encoding.UTF8))
            {
                string? info = sr.ReadLine();
                while (!String.IsNullOrEmpty(info))
                {
                    string[] ss = info.Split('\t');
                    string dwPy = PinYinConverter.GetFirst(ss[1]);
                    DW dw = new ()
                    {
                        Dwm = ss[0],
                        Dwmch = ss[1],
                        DwPy = dwPy,
                        StarTime = ss[3],
                    };
                    dwList.Add(dw);
                    info = sr.ReadLine();
                }
            }
        }
        private void ShowInfo()
        {
            //reject.Visible = false;
            if (Idx > LetterList.Count || Idx <= 0)
            {
                return;
            }
            LetterNow = LetterList[Idx-1];

                    
            WhenDateChange();

            string title = LetterNow.Name;
            var info = GetInfo(title);

            ReNameText = info.CompInfo;
            if(LetterNow.Name.Split('_').Count()==0)
            {
                view.Title =LetterNow.Name;
            }
            else
            {
                if (LetterNow.Name.Split('_').Length>=3)
                    view.Title = LetterNow.Name.Split('_')[2];
                else
                    view.Title = "无信息";
            }             
            string path = LetterNow.Path;
            string hash = HashHelper.GetFileHash256(LetterNow.Path);
            if(LetterDatas!=null&&LetterDatas.Count!=0&& LetterDatas.Where(a => a.Hash == hash).Count()!=0)
            {
                HasFile = true;
                LetterData letter = LetterDatas.First(a => a.Hash == hash);
                string format = "yyyyMMdd";
                string cachedPath = Path.Combine(Directory.GetCurrentDirectory(), "cached", hash + ".jpg");
                if (Path.Exists(cachedPath))
                {
                    IsCachePic = true;
                    ImgNow = BitmapToBitmapImage(cachedPath);
                }
                else
                {
                    ImgNow = BitmapToBitmapImage(LetterNow.Path);
                }
                DateTime.TryParseExact(letter.StarTime, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date1);
                DateTime.TryParseExact(letter.EndTime, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date2);
                var hasSignDate=DateTime.TryParseExact(letter.SignDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date3);
                StartDate = date1;
                EndDate = date2;
                SignDate = hasSignDate == false ? date1 : date3;
                ReNameText = letter.Dwmch;
                if(LockTag)
                {
                    if (letter.Tag?.Count>0)
                    {
                        TagText = string.Join(',', letter.Tag.ToArray());
                    }
                    if(!String.IsNullOrEmpty(letter.Bank))
                    {
                        SelectedBank = letter.Bank ?? Banks[0];
                    }
                }
                else
                {
                    TagText = string.Join(',', letter.Tag.ToArray());
                    SelectedBank = letter.Bank ?? Banks[0];
                }

            }
            else
            {
                ImgNow = BitmapToBitmapImage(LetterNow.Path);
                HasFile = false;
                if (existsFile.ContainsKey(hash))
                {
                    var fi = existsFile[hash];
                    string[] ss = Path.GetFileNameWithoutExtension(fi.FullName).Split('_');
                    string format = "yyyyMMdd";
                    DateTime.TryParseExact(ss[0], format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date1);
                    DateTime.TryParseExact(ss[1], format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date2);
                    if(ss.Length>3)
                    {
                        var hasSignDate = DateTime.TryParseExact(ss[3], format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date3);
                        SignDate = hasSignDate == false ? date1 : date3;
                    }

                    StartDate = date1;
                    EndDate = date2;
                    ReNameText = ss[2];
                }
            }
            //label3.Text = now.Value.ToString();
        }

        private void WhenDateChange()
        {
            var all = dwList.Where(a => a.StarTime == StartDate.ToString("yyyyMMdd")).Select(a => a.Dwmch);
            //dwCB.Items.Clear();
            //dwCB.Items.AddRange(all.ToArray());
            //if (dwCB.Items.Count == 1)
            //{
            //    editText.Text = dwCB.Items[0].ToString();
            //}
        }

        private (DateTime date, string CompInfo) GetInfo(string title)
        {
            string[] s = title.Split('_');
            if (s.Length < 2) {
                return (new DateTime(DateOnly.MinValue, TimeOnly.MinValue), "查无此单位");
            }
            string format = "yyyyMMdd";
            bool re=DateTime.TryParseExact(s[1], format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date);
            if (re&&date>DateTime.Now.AddYears(-20))
                return (date, s[2]);
            else
                return (new DateTime(DateOnly.MinValue, TimeOnly.MinValue), "查无此单位");
        }
        private async Task UpdateFileInfo(string hash,string filePath)
        {
            if (isSaving)
                return;
            isSaving = true;
            existsFile.Remove(hash);

            await Task.Run(() =>
            {
                FileInfo fi = new FileInfo(filePath);
                if (!existsFile.ContainsKey(HashHelper.GetFileHash256(fi.FullName)))
                {
                    existsFile.Add(HashHelper.GetFileHash256(fi.FullName), fi);
                }
            });
            isSaving = false;
        }
        private async Task UpdateFileInfo()
        {
            if (isSaving)
                return;
            isSaving = true;
            existsFile.Clear();
            var saveDir = new DirectoryInfo(Directory.GetCurrentDirectory() + "\\book\\");
            Dictionary<string, FileInfo> pairs = new Dictionary<string, FileInfo>();
            await Task.Run(() =>
            {
                foreach (var file in saveDir.GetFiles())
                {
                    if (!existsFile.ContainsKey(HashHelper.GetFileHash256(file.FullName)))
                    {
                        existsFile.Add(HashHelper.GetFileHash256(file.FullName), file);
                    }
                }
            });
            isSaving = false;
        }
        /// <summary>
        /// 放大
        /// </summary>
        [RelayCommand]
        private void ZoomIn()
        {
            zoom = zoom < sizeList.Length - 1 ? zoom + 1 : zoom;
            if (IsCachePic)
            {
                IsCachePic = false;
                ImgNow = BitmapToBitmapImage(LetterNow.Path);
            }
            view.picBox.Height = (double)sizeList[zoom].Height;
            view.picBox.Width = (double)sizeList[zoom].Width;
        }
        /// <summary>
        /// 缩小
        /// </summary>
        [RelayCommand]
        private void ZoomOut()
        {
            zoom = zoom > 0 ? zoom - 1 : 0;
            if (IsCachePic)
            {
                IsCachePic = false;
                ImgNow = BitmapToBitmapImage(LetterNow.Path);
            }
            view.picBox.Height = (double)sizeList[zoom].Height;
            view.picBox.Width = (double)sizeList[zoom].Width;
        }
        /// <summary>
        /// 重置
        /// </summary>
        [RelayCommand]
        private void ResetPic()
        {
            zoom = 2;
            if (IsCachePic)
            {
                IsCachePic = false;
                ImgNow = BitmapToBitmapImage(LetterNow.Path);
            }
            view.picBox.Height = (double)sizeList[zoom].Height;
            view.picBox.Width = (double)sizeList[zoom].Width;
        }
        /// <summary>
        /// 下一张
        /// </summary>
        [RelayCommand]
        private void Next()
        {
            if (AutoSave)
            {
                Save();
            }
            if (Idx >= 0&& Idx < LetterList.Count)
            {
                Idx += 1;
                ShowInfo();
            }
            Cached();
        }

        /// <summary>
        /// 前一张
        /// </summary>
        [RelayCommand]
        private void Pre()
        {
            if (Idx>1)
            {
               Idx -= 1;
               ShowInfo();
            }
        }

        [RelayCommand]
        private void Jump()
        {
            if (AutoSave)
            {
                Save();
            }
            if (Idx > 0 && Idx <= LetterList.Count)
            {
                ShowInfo();
            }
            Cached();
            JumpVis = false;
        }
        [RelayCommand]
        private void SaveLetterXml()
        {
            OpenFolderDialog openFolderDialog = new OpenFolderDialog();
            if (!openFolderDialog.ShowDialog().HasValue)
                return;
            string folderPath = openFolderDialog.FolderName;
            LetterDataCollection letterDatas = LetterDataCollection.FromEnumerable(LetterList);
            DirectoryInfo dir = new DirectoryInfo(folderPath);
            string path = Path.Combine(dir.Name + ".xml");
            LetterDataUtils.SaveToFile(letterDatas, path);
        }

        [RelayCommand]
        private async void Ocr()
        {

            var fi = new FileInfo(LetterNow.Path);
            string filePaht = CachedOcrTemp(fi.FullName);
            string url = $"http://127.0.0.1:5000/ocr?file_path={filePaht}";
            WebClient webClient = new WebClient();
            var json = webClient.DownloadString(url);
            JObject jObject = JObject.Parse(json);

            // 访问解构后的属性
            string dw = (string)jObject["dw"];
            string date = (string)jObject["date"];
            if(!string.IsNullOrEmpty(dw))
            {
                var result = System.Windows.MessageBox.Show($"是否同意将单位名称【{ReNameText}】==>【{dw.Trim()}】", "确认", MessageBoxButton.OKCancel);
                ReNameText = dw.Trim();
            }
            if(!string.IsNullOrEmpty(date)&&DateTime.TryParse(date.Trim(),out DateTime date1))
            {
                var result = System.Windows.MessageBox.Show($"是否同意将开始时间【{StartDate.ToString("yyyyMMdd")}】==>【{date1.ToString("yyyyMMdd")}】", "确认",MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    StartDate = date1;

                }
            }

            Debug.WriteLine(dw); // 输出: extracted_content
            Debug.WriteLine(date); // 输出: 2023-10-05 14:48:29.764（根据当前时区）
        }

        [RelayCommand]
        private void ReadLetterXml()
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            openFileDialog.Filter = "*.xml|*.xml";
            openFileDialog.ShowDialog();
            if (openFileDialog.FileNames.Count() == 0)
                return;
            string filePath = openFileDialog.FileName;
            XmlFile = filePath;
            LetterDatas = LetterDataUtils.LoadFromFile(filePath);
            var temp= LetterDatas.ToCloneEnumerable();
            LetterList.Clear();
            WordCompare.init(LetterDatas.Select(a=>a.Dwmch));

            temp.ToList().ForEach(x => LetterList.Add(x));
            UpdateFileInfo();
            Idx = 1;
            ShowInfo();
        }


        /// <summary>
        /// 忽略照片文件另存为
        /// </summary>
        [RelayCommand]
        private void Igon()
        {
            var pic = ImgNow;
            var fi=new FileInfo(LetterNow.Path);
            string fileName = fi.Name;
            string fatherPath = fi.DirectoryName;
            string igonDir = Path.Combine(fatherPath, "igon");
            string IgonPath= Path.Combine(igonDir, fileName);
            if (!Directory.Exists(igonDir))
                Directory.CreateDirectory(IgonPath);
            File.Move(LetterNow.Path, IgonPath);
            int idxTemp = Idx;
            LetterList.Remove(LetterNow);
            if (LetterList.Count > 0)
            {
                Idx = idxTemp;
                ShowInfo();
            }
            UpdateFileInfo();
        }

        [RelayCommand]
        private void Search()
        {
            var nameSearched=LetterDataUtils.FindByName(LetterDatas, SearchText);
            var temp = LetterDataCollection.FromEnumerable(nameSearched.AsEnumerable());
            var resultDatas = LetterDataUtils.FindByTag(temp, TagText);
            LetterList.Clear();
            resultDatas.ToList().ForEach(x => LetterList.Add(new Letter(x.Name,x.Path)));
            Idx = 1;
            ShowInfo();
        }

        internal void removeLetterMeta(string letterPath)
        {
            MetaData oldMeta = MetaData.FromFile(letterPath);
            LetterData letterData = LetterData.FromMeta(oldMeta);
            //将XML文件中该图片信息先清空
            LetterDataUtils.RemoveLetterData(XmlFile, letterData);
            //缓存该文件的信息也清空
            existsFile.Remove(oldMeta.Hash);
        }

        [RelayCommand]
        private void Save()
        {
            byte samePath = 1 << 1;
            byte sameHash = 1 << 2;
            byte saveOver = 1 << 3;

            byte state = 0;


            string name = ReNameText;
            string time = StartDate.ToString("yyyyMMdd");
            string time2 = EndDate.ToString("yyyyMMdd");
            string time3 = SignDate.ToString("yyyyMMdd");

            var disPlayPic = ImgNow;
            string localDir = Directory.GetCurrentDirectory();
            string fileName=string.Join('_',time,time2,name,time3)+JPGD;
            string savePath = Path.Combine(localDir, "book", fileName);

            BookSaveProcess bookprocess = new(this, disPlayPic, savePath, LetterNow.Path);
            bookprocess.Init();
            
            ////先处理是否有同名文件
            //if (File.Exists(savePath))
            //{
            //    state |= samePath;
            //    PicCompareWindow picCompare = new PicCompareWindow(savePath, disPlayPic);
            //    bool? diaglogResult = picCompare.ShowDialog();
            //    var replace = diaglogResult.HasValue && diaglogResult.Value;
            //    //不需要替换则直接返回
            //    if (!replace)
            //        return;
            //    //先剔除要保存的文件已存在Meta信息
            //    removeLetterMeta(savePath);
            //    //如果是同一个文件，只需要完成图片自更新
            //    if (savePath == LetterNow.Path)
            //    {
            //        disPlayPic.Update(savePath);
            //        state |= saveOver;
            //    }
            //    //如果不是同一个文件，则先将原文件移动
            //    else if (!string.IsNullOrEmpty(savePath))
            //    {
            //        // 获得父目录路径
            //        string parentPath = Path.GetDirectoryName(savePath)!;
            //        string delDir = Path.Combine(parentPath, "del");
            //        Directory.CreateDirectory(delDir);
            //        // 构建新路径并移动文件
            //        File.Move(savePath, Path.Combine(delDir, fileName));
            //        state &= (byte)~samePath;
            //    }
            //}
            ////上述步骤结束后，如果名字一致的则需要完成替换。原先的文件，如果文件名和现在图片名一致，则只要更新。
            ////如果不一致，说明是新的委托书，则把之前的委托书的。xml及缓存meta清空，原文件移位。但是，还没有到替换这一步。

            //string hash = HashHelper.GetFileHash256(LetterNow.Path);
            //if(existsFile.TryGetValue(hash, out var fi)) 
            //{
            //    state |= sameHash;
            //    if (fi.FullName != savePath)
            //    {
            //        string nameNew = Path.GetFileNameWithoutExtension(savePath);
            //        string nameOld = Path.GetFileNameWithoutExtension(fi.FullName);
            //        if (MessageBoxResult.Yes == System.Windows.MessageBox.Show($"该文件已存在，是否将名称从【{nameOld}】-->【{nameNew}】", "提示", MessageBoxButton.YesNo))
            //        {
            //            File.Move(fi.FullName, savePath);
            //        }
            //        else
            //        {
            //            return;
            //        }
            //    }
            //}
            //else if((state&saveOver)!=saveOver)
            //{
            //    File.Copy(LetterNow.Path, savePath);
            //}
            //saveData(savePath);
        }
        internal void saveData(string savePath)
        {

            MetaData oldMeta = MetaData.FromFile(savePath);
            LetterData letter = LetterData.FromMeta(oldMeta);

            if (!String.IsNullOrEmpty(TagText))
            {
                var tagArr = TagText.Split(',', '，', '|', '、', '\\');
                letter.Tag = tagArr.ToList();
            }
            letter.Bank = SelectedBank;
            LetterDataUtils.AddOrUpdateLetterData(XmlFile, letter);
            
            string hash = HashHelper.GetFileHash256(savePath);
            _ = Task.Run(async () =>
            {
                await UpdateFileInfo(hash, savePath).ConfigureAwait(false);
                Debug.WriteLine(string.Join("", DateTime.Now.ToShortTimeString(), $"【{savePath}】更新完毕"));
            });

        }

        [RelayCommand]
        private void EmpBook()
        {
            OpenFolderDialog openFolderDialog = new OpenFolderDialog();
            openFolderDialog.Title = "请选择委托书文件夹";
            openFolderDialog.DefaultDirectory = Directory.GetCurrentDirectory();
            if (!(openFolderDialog.ShowDialog() ?? false))
                return;
            string dirPath = openFolderDialog.FolderName;
            string savePath=Path.Combine(dirPath, LetterNow.Name + ".jpg");

            File.Copy(LetterNow.Path, savePath,true);
        }

        private void Cached()
        {
            string hash = HashHelper.GetFileHash256(LetterNow.Path);
            string cachedPath = Path.Combine(Directory.GetCurrentDirectory(), "cached", hash + ".jpg");
            if (!Path.Exists(Path.Combine(Directory.GetCurrentDirectory(), "cached")))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "cached"));
            }
            if (!File.Exists(cachedPath))
            {
                using (Bitmap originalImage = new Bitmap(LetterNow.Path))
                {
                    // 调整大小
                    Bitmap resizedImage = ImageUtil.ResizeImageToWidth(originalImage, 610);

                    // 保存调整大小后的图像
                    resizedImage.Save(cachedPath, ImageFormat.Png);
                }
            }
        }
        private static string CachedOcrTemp(string filePath)
        {
            string temp = Path.GetTempPath();
            string hash = HashHelper.GetFileHash256(filePath);

            string cachedPath = Path.Combine(temp, "cached", hash + ".jpg");

            if (!Directory.Exists(Path.Combine(temp, "cached")))
            {
                Directory.CreateDirectory(Path.Combine(temp, "cached"));
            }

            if (!File.Exists(cachedPath))
            {
                using (Bitmap originalImage = new Bitmap(filePath))
                {
                    int originalWidth = originalImage.Width;
                    int originalHeight = originalImage.Height;
                    Bitmap resizedImage = ImageUtil.ResizeImageToWidth(originalImage, 600);

                    // 按上部2/7的比例调整大小
                    int targetHeight = (int)(resizedImage.Height* 2 / 7);
                    int targetWidth =600;
                    Bitmap backImg = new Bitmap(targetWidth,targetHeight);

                    using (Graphics g = Graphics.FromImage(backImg))
                    {
                        g.DrawImage(resizedImage, new Rectangle(0, 0, targetWidth, targetHeight), new Rectangle(0, 0, targetWidth, targetHeight), GraphicsUnit.Pixel);
                    }

                    backImg.Save(cachedPath, ImageFormat.Png);
                }
            }

            return cachedPath;
        }

        private static string CachedTemp(string filePath)
        {
            string temp=Path.GetTempPath();
            string hash = HashHelper.GetFileHash256(filePath);
            
            string cachedPath = Path.Combine(temp, "cached", hash + ".jpg");
            if (!Path.Exists(Path.Combine(temp, "cached")))
            {
                Directory.CreateDirectory(Path.Combine(temp, "cached"));
            }
            if (!File.Exists(cachedPath))
            {
                using (Bitmap originalImage = new Bitmap(filePath))
                {
                    // 调整大小
                    Bitmap resizedImage = ImageUtil.ResizeImageToWidth(originalImage, 600);

                    // 保存调整大小后的图像
                    resizedImage.Save(cachedPath, ImageFormat.Png);
                }
            }
            return cachedPath;
        }

        private void SaveBitmapImage(BitmapImage bitmapImage, string filePath)
        {
            // 检查是否提供了有效的BitmapImage
            if (bitmapImage == null || bitmapImage.IsFrozen || bitmapImage.UriSource != null)
            {
                throw new ArgumentException("BitmapImage is not valid for saving.");
            }

            // 创建一个内存流来临时保存图像
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // 使用Png编码器将BitmapImage编码为字节数组
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
                encoder.Save(memoryStream);

                // 将内存流的位置重置到开始以便读取
                memoryStream.Position = 0;

                // 将内存流的内容写入到指定的文件路径
                using (FileStream fileStream = File.OpenWrite(filePath))
                {
                    memoryStream.CopyTo(fileStream);
                }
            }
        }
        private Bitmap LoadRotePic(string imagePath)
        {
            Bitmap rotatedImage = null;
            using (Bitmap originalImage = new Bitmap(imagePath))
            {
                // 检查图片高度是否小于宽度
                if (originalImage.Height < originalImage.Width)
                {
                    rotatedImage = new Bitmap(originalImage.Height, originalImage.Width);
                    using (var g = Graphics.FromImage(rotatedImage))
                    {
                        // 设置旋转中心点为图片中心
                        g.TranslateTransform(rotatedImage.Width / 2, rotatedImage.Height / 2);
                        // 旋转90度
                        g.RotateTransform(90);

                        // 绘制旋转后的图片
                        g.DrawImage(originalImage, new RectangleF(-originalImage.Width / 2, -originalImage.Height / 2, originalImage.Width, originalImage.Height));

                        //graphics.DrawImage(originalImage, new Point(0, 0));
                    }

                    return rotatedImage;
                }
                else
                {
                    Console.WriteLine("图片的高度不小于宽度，无需旋转。");
                    rotatedImage = (Bitmap)originalImage.Clone();
                }
            }
            return rotatedImage;
        }
       
        private BitmapImage BitmapToBitmapImage(string path)
        {
            if(!IsCachePic)
            {
                using (Bitmap bmp = LoadRotePic(path))
                {
                    using (MemoryStream memory = new MemoryStream())
                    {
                        // 将Bitmap保存为PNG格式到内存流中  
                        // 注意：你也可以选择其他格式，如JPEG，但记得更改BitmapEncoder  
                        bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                        memory.Position = 0;

                        // 从内存流中创建BitmapImage  
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.BeginInit();
                        bitmapImage.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                        bitmapImage.UriSource = null;
                        bitmapImage.StreamSource = memory;
                        bitmapImage.EndInit();
                        // 冻结BitmapImage，使其变为不可变，以提高性能  
                        bitmapImage.Freeze();
                        return bitmapImage;
                    }
                }
            }
            else
            {
                var uriPath= Path.GetFullPath(path); // 解析相对路径和 ..\
                Uri uri = new Uri(uriPath);
                var bmp= new BitmapImage(uri);
                bmp.Freeze();
                return bmp;
            }
        }
        private BitmapImage BitmapToBitmapImage(Bitmap bitmap)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                // 将Bitmap保存为PNG格式到内存流中  
                // 注意：你也可以选择其他格式，如JPEG，但记得更改BitmapEncoder  
                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                memory.Position = 0;

                // 从内存流中创建BitmapImage  
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.UriSource = null;
                bitmapImage.StreamSource = memory;
                bitmapImage.EndInit();

                // 冻结BitmapImage，使其变为不可变，以提高性能  
                bitmapImage.Freeze();

                return bitmapImage;
            }
        }
    }
}
